﻿using System;
using zijian666;
using zijian666.Abstractions;
using zijian666.Convertor.Base;
using zijian666.Core;
using zijian666.ConvertExtensions;

namespace zijian666.Convertor;

/// <summary>
/// <seealso cref="DateTime" /> 转换器
/// </summary>
public class DateTimeConvertor : FromConvertor<DateTime>
                               , IFrom<object, DateTime>
                               , IFromTime<DateTime>
{
    /// <inheritdoc/>
    public ConvertResult<DateTime> From(IConvertContext context, DateTimeOffset input) => new(input.LocalDateTime);

    /// <inheritdoc/>
    public ConvertResult<DateTime> From(IConvertContext context, object input)
    {
        var r = context.Convert<DateTimeOffset>(input);
        if (r.Success)
        {
            return new(r.Value.LocalDateTime);
        }
        return context.ConvertFail(this, input, r.Exception);
    }

    /// <inheritdoc/>
    public ConvertResult<DateTime> From(IConvertContext context, DateTime input) => new(input);

    /// <inheritdoc/>
    public ConvertResult<DateTime> From(IConvertContext context, TimeSpan input)
        => UTCHelper.LocalEpoch.Add(input);

#if NET5_0_OR_GREATER
    /// <inheritdoc/>
    public ConvertResult<DateTime> From(IConvertContext context, TimeOnly input)
        => new(UTCHelper.LocalEpoch.Add(input.ToTimeSpan()));

    /// <inheritdoc/>
    public ConvertResult<DateTime> From(IConvertContext context, DateOnly input)
        => new(input.ToDateTime(TimeOnly.MinValue));
#endif
}
